// var URL_ip = "http://xman-tech.cn/yeekitdoctrans-feature";
// var URL_ip = "http://192.168.34.135:9199";
var URL_ip = "http://xman-tech.cn/yeekitdoctrans-daxing/";
// var URL_ip = "http://xdoc.yeekit.com/yeekitdoctrans/";
// var URL_ip = "http://192.168.34.137:9200";
var Project_ip = window.location.pathname.slice(0, window.location.pathname.indexOf('/', 2) + 1);
var isOldPassWord = false;
var isNewPassword = false;
var isConfrimPassword = false;
updateUserStatus(sessionStorage['userId'], sessionStorage['userName']);
/*if(window.location.href!=self.location.origin+'/index.html'&&!sessionStorage['token']){
	window.location.href=''+'index.html'
}*/
/***********************************用户信息状态显示********************************/
$(".cancel").click(function () {
    $("#changePasswordWindow").css("display", "none");
})
$("#closeButton").click(function () {
    $("#changePasswordWindow").css("display", "none");
})
$("#changePassword").click(function () {
    $("#changePasswordWindow").css("display", "");
});
function verifyNewPassword(){
    let res = /[^\a-\z\A-\Z0-9\.\,\.\?]/g;
    var newPassword = $("#newPassword").val();
    var value = res.test(newPassword);
    if(newPassword.length < 6 || newPassword.length > 14){
        $("#isNewPassWordErrorShown").show();
        $("#isNewPassWordErrorShown").html("密码长度为6~14位");
        isNewPassword = false;
    } else if (!value) {
        $("#isNewPassWordErrorShown").hide();
        isNewPassword = true;
    } else {
        $("#isNewPassWordErrorShown").show();
        isNewPassword = false;
        $("#isNewPassWordErrorShown").html("密码只能包含字母、数字或标点符号");
    }
}
function validationOldPassword(){
    var oldPassword = $("#oldPassword").val();
    console.log(1);
    if(oldPassword.trim() == ""){
        $("#isOldPasswordErrorShown").css("display", "");
        isOldPassWord = false;
    } else {
        $("#isOldPasswordErrorShown").css("display", "none");
        isOldPassWord = true;
    }
}
function validationNewPassword(){
    var newPassword = $("#newPassword").val();
    var confrimPassword = $("#confrimPassword").val();
    if (confrimPassword == newPassword){
        $("#isConfrimNewPasswordErrorShown").css("display", "none");
        isConfrimPassword = true;
    } else {
        $("#isConfrimNewPasswordErrorShown").css("display", "");
        isConfrimPassword = false;
    }
}
function uploadPassword(){
    validationOldPassword();
    validationNewPassword();
    verifyNewPassword();
    let id = sessionStorage['userId'];
    var newPassword = $("#newPassword").val();
    var oldPassword = $("#oldPassword").val();
    var data = {
        'userId':id,
        'new_password':newPassword,
        'old_password':oldPassword
    };
    if(isConfrimPassword && isOldPassWord && isNewPassword){
        $.ajax({
            url:URL_ip+'/user/updatePwd',
            type:'post',
            contentType: 'application/json',
            dataType: 'json',
            data:JSON.stringify(data),
            beforeSend: function(request) {
                request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
            },
            error: function(XMLHttpRequest) {
                //失败原因
                timeOut_error(XMLHttpRequest);
            },
            success:function(data){
                if(data.code == 1){
                    alert("修改成功，请重新登录");
                    setTimeout(() => {
                        logout();
                    }, 1000);
                } else if (data.code == 2){
                    alert("参数缺失");

                } else if (data.code == 3){
                    alert("原密码错误");

                } else if (data.code == 4){
                    alert("修改失败");

                }
            }
        })
    }
}
//图片验证码

function getImage(num) {
    $.ajax({
        url: URL_ip + "/captcha/getImageVeriftyCodeURL",
        type: "get",
        beforeSend: function() {
            //注册
            if(num==0) {
                $("#login-change").hide();
                $("#login-change").next('.loading_img').show();
            } else if(num==1){
                $("#image-change").hide();
                $("#image-change").next('.loading_img').show();
            }else if(num==2){
                $("#image-authenticate").hide();
                $("#image-authenticate").next('.loading_img').show();
            }
        },
        error: function(error) {
            //失败原因
        },
        success: function(data) {
            if(data.code == "1") {
                //注册
                if(num==0) {
                    console.log(data)
                    $("#login-change").next('.loading_img').hide();
                    imageCodeKey_login = data.data.key;
                    $("#login-change").attr('src', data.data.imageUrl);
                    $("#login-change").show();
                }
                // }else if(num==1){
                //     $("#image-change").next('.loading_img').hide();
                //     imageCodeKey = data.data.key;
                //     $("#image-change").attr('src', data.data.imageUrl);
                //     $("#image-change").show();
                // }else if(num==2){
                //     $("#image-authenticate").next('.loading_img').hide();
                //     imageCodeKey_authenticate = data.data.key;
                //     $("#image-authenticate").attr('src', data.data.imageUrl);
                //     $("#image-authenticate").show();
                // }

            }
        }
    })
}
//看不清切换图片
$("#header_Land").click(function() {
    clearLogin();
})
//清除登录数据
function clearLogin(){
    getImage(0);
    $('#login-form p[class="red"]').each(function() {
        $(this).remove();
    })
    $("#login-phone").val('');
    $("#login-password").val('');
    $("input[name='imageCode']").val('');
}
$("#register-box").click(function() {
    clearRegister();
})


function updateUserStatus(uid, uname) {
    if(sessionStorage['token']) {
        //用户信息显示
        $("#changePassword").css("display","");
        $('#header_Land').css('display', 'none');
        $('#user_list').css('display', 'block');
        $("#user_list > ul > li").eq(0).html(uname);
        $("#user_list > ul > li").eq(0).attr('title', uname);
        $("#user_list > ul > li").eq(0).attr('id', uid);
    } else {
        $("#changePassword").css("display","none");
        $('#user_list').css('display', 'none');
        $('#header_Land').css('display', 'block');
    }
}

/***********************************登录注册部分********************************/
$("#register-box").click(function(){
    clearRegister();
})
//清除注册数据
function clearRegister() {
    $('#registered-form p[class="red"]').each(function() {
        $(this).remove();
    })
    $('#registered-form input').each(function() {
        $(this).val('');
    })
    $("#register").attr('disabled', true)
}
$("#login-box").click(function() {
    clearLogin();
})
//清除登录数据
function clearLogin() {
    getImage(0);
    $('#login-form p[class="red"]').each(function() {
        $(this).remove();
    })
    $("#login-phone").val('');
    $("#login-password").val('');
    $("input[name='imageCode']").val('');
}

//手机号合法性
$("#phone").blur(function() {
    $(this).closest('p').next('.red').remove();
    if(!this.value) {
        //$('<p class="red">请输入手机号!</p>').insertAfter($(this).closest('p'));
    } else {
        var nospace = this.value.replace(/\s/g, "");
        $(this).val(nospace);
        var data = {
            'username': this.value
        };
        $.ajax({
            url: URL_ip + "/register/ucCheckeUsername",
            type: "post",
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(data),
            error: function(error) {
                //失败原因
                console.log(error);
            },
            success: function(data) {
                if(data.code == "2") {
                    $('<p class="red">该用户名已存在</p>').insertAfter($("#phone").closest('p'));
                } else if(data.code == "3") {
                    $('<p class="red">检查用户名失败</p>').insertAfter($("#phone").closest('p'));
                }
                if(data.code == '1') {
                    $("#register").removeClass('notCheck');
                    $("#register").attr('disabled', false);
                }
            }
        })
    }
})
$("#Password").blur(function() {
    $("#Password").closest('p').next('.red').remove();
    var re = /^[0-9a-zA-Z_-]{6,20}$/;
    if(!re.test($('#Password').val()) && $('#Password').val()) {
        $('<p class="red">请输入不小于6位数的密码!</p>').insertAfter($("#Password").closest('p'));
    }
})
$("#login-password").blur(function() {
    $(this).closest('p').next('.red').remove();
})

$("#login-phone").blur(function() {
    $(this).closest('p').next('.red').remove();
    var nospace = this.value.replace(/\s/g, "");
    $(this).val(nospace);
})
//注册账号
$("#register").click(function() {
    var data = getFormJson("#registered-form");
    $("#message").closest('p').next('.red').remove();
    if(data && !$('#registered-form p[class="red"]').length && data.password) {
        $.ajax({
            url: URL_ip + "/register/ucRegisterMember",
            type: "post",
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(data),
            error: function(error) {
                //失败原因
                console.log(error);
            },
            success: function(data) {
                if(data.code == 4) {
                    $('<p class="red">注册失败</p>').insertAfter($("#Password").closest('p'));
                }
                if(data.code == -1) {
                    $('<p class="red">用户已存在</p>').insertAfter($("#Password").closest('p'));
                }
                if(data.code == 1) {
                    //alert(data.message + '可以去登录了');
                    $("#response_mark_works").text('注册成功！为您自动跳转登录 ');
                    $("#response_mark").fadeIn();
                    setTimeout(function() {
                        $("#response_mark").fadeOut();
                        $('#registered-form p[class="red"]').each(function() {
                            $(this).remove();
                        })
                        $('#registered-form input').each(function() {
                            $(this).val('');
                        })
                        $("input[name='imageCode']").val('');
                        liStatus($(".state li").eq(0));
                    }, 1000)

                }
            }
        })
    } else {
        if(!data.password) {
            $('<p class="red">密码不能为空</p>').insertAfter($("#Password").closest('p'));
        }

    }

})

//登录账号
$("#Land").click(function() {
    var data = getFormJson("#login-form");
    data.key = imageCodeKey_login;
    $("#login-password").closest('p').next('.red').remove();
    $("#login-change").closest('p').next('.red').remove();
    if(!$('#login-form p[class="red"]').length && data.username && data.password) {
        $.ajax({
            url: URL_ip + "/login/ucLoginMember",
            type: "post",
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(data),
            error: function(error) {
                //失败原因
            },
            success: function(data, status, request) {
                console.log(data)
                if(data.code == 1) {
                    sessionStorage['currentPage'] = 1;
                    sessionStorage['userId'] = data.data.userId;
                    sessionStorage['userName'] = data.data.userName;
                    sessionStorage['token'] = request.getResponseHeader("X-OAUTH-TOKEN");
                    updateUserStatus(data.data.userId, data.data.userName);
                    $(".box").hide();
                    $(".header").css("opacity", "1");
                    window.location.reload();
                }
                if(data.code == 2) {
                    $('<p class="red">图片验证码不正确</p>').insertAfter($("#login-change").closest('p'));
                }
                if(data.code == 3) {
                    $('<p class="red">图片验证码为空</p>').insertAfter($("#login-change").closest('p'));
                }
                if(data.code == 5) {
                    $('<p class="red">图片验证码已过期</p>').insertAfter($("#login-change").closest('p'));
                }
                if(data.code == -1) {
                    $("#response_mark_works").text('账号未注册，请先注册!');
                    $("#response_mark").fadeIn();
                    setTimeout(function() {
                        $("#response_mark").fadeOut();
                        // liStatus($(".state li").eq(1));
                        // $('#registered-form p[class="red"]').each(function() {
                        // 	$(this).remove();
                        // })
                        // $('#registered-form input').each(function() {
                        // 	$(this).val('');
                        // })
                    }, 1000)

                }
                if(data.code == -2) {
                    $('<p class="red">密码错误</p>').insertAfter($("#login-password").closest('p'));
                }
                if(data.code == 13) {
                    $("#response_mark_works").text('登录失败，请重新登录 ');
                    $("#response_mark").fadeIn();
                    setTimeout(function() {
                        $("#response_mark").fadeOut();
                        $('#registered-form p[class="red"]').each(function() {
                            $(this).remove();
                        })
                        $('#registered-form input').each(function() {
                            $(this).val('');
                        })
                    }, 1000)

                }
            }
        })
    } else {
        if(!data.username) {
            $("#login-phone").closest('p').next('.red').remove();
            $('<p class="red">账号不能为空</p>').insertAfter($("#login-phone").closest('p'));
        } else if(!data.imageCode) {
            $('<p class="red">验证码不能为空</p>').insertAfter($("#login-change").closest('p'));
        } else if(!data.password) {
            $('<p class="red">密码不能为空</p>').insertAfter($("#login-password").closest('p'));
        }
    }

})

$(".state li").click(function() {
    liStatus($(this));
    //另一种方法: $("div").eq($(".tab li").index(this)).addClass("on").siblings().removeClass('on');
});

function liStatus(obj) {
    $(".state li").eq($(obj).index()).addClass("cur").siblings().removeClass('cur');
    if($(obj).index() == 1 && !$("#register").hasClass('notCheck')) {
        $("#register").addClass('notCheck');
        $("#register").attr('disabled', true);
    }
    $(".LandingInformation").hide().eq($(obj).index()).show();
}
//退出登录
$("#logout").click(function() {
    $.ajax({
        url: URL_ip + "/logout/logoutMember",
        type: "post",
        dataType: 'json',
        contentType: 'application/json',
        data: "",
        beforeSend: function(request) {
            request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
        },
        error: function(error) {
            //失败原因
        },
        success: function(data) {
            if(data.code == 1) {
                window.location.href=''+'index.html';
                sessionStorage.clear();
                updateUserStatus(false, false);
            }
        }
    })
})
function logout() {
    $.ajax({
        url: URL_ip + "/logout/logoutMember",
        type: "post",
        dataType: 'json',
        contentType: 'application/json',
        data: "",
        beforeSend: function(request) {
            request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
        },
        error: function(error) {
            //失败原因
        },
        success: function(data) {
            if(data.code == 1) {
                window.location.href=''+'index.html';
                sessionStorage.clear();
                updateUserStatus(false, false);
            }
        }
    })

}

/***********************************公共方法********************************/
//超时报错
function timeOut_error(XMLHttpRequest) {
    console.log(XMLHttpRequest);
    if(XMLHttpRequest.status == 403) {
        alert("登录超时");
        sessionStorage.clear();
        window.location.href = '' + 'index.html';
        updateUserStatus(false, false);
    }
}
//获取内容显示屏高度
var minHeight = $(document.body).outerHeight(true) - $('footer').outerHeight(true);
$('.content').css('min-height', minHeight + 'px');

function getFormJson(obj) { //frm：form表单的id
    var o = {};
    var a = $(obj).serializeArray();
    $.each(a, function() {
        if(o[this.name] !== undefined) {
            if(!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}

function showLogin(i) {
    $('.state').show();
    if(i == 0) {
        clearLogin();
    } else {
        if(!$("#register").hasClass('notCheck')) {
            $("#register").addClass('notCheck');
            $("#register").attr('disabled', true);
        }
        clearRegister();
    }
    $(".box").show();
    $(".Land").show();
    $(".header").css("opacity", "0.5")
    $(".state li").eq(i).addClass("cur").siblings().removeClass('cur');
    $(".LandingInformation").hide().eq(i).show();
}
/**************************************保存语言********************************************/
saveSrcLen();

function saveSrcLen() {
    $.ajax({
        url: URL_ip + "/getSrcLan",
        type: "post",
        error: function(error) {
            //失败原因
        },
        success: function(data) {
            if(data.code == 0) {
                sessionStorage['srcLan'] =dealData(data.data);
                console.log(sessionStorage['srcLan']);
                saveDestLen();
            }
        }
    })
}

function saveDestLen() {
    var data = {
        "languageId":0
    };
    for(var attr in JSON.parse(sessionStorage['srcLan'])){
        data.languageId=JSON.parse(sessionStorage['srcLan'])[attr];
        break;
    }
    $.ajax({
        url: URL_ip + "/getDestLan",
        type: "post",
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(data),
        error: function(error) {
            //失败原因
        },
        success: function(data) {
            console.log(data);
            if(data.code == 0) {
                sessionStorage['destLan'] = dealData(data.data);
                console.log(sessionStorage['destLan'])
            }
        }
    })
}
function dealData(data) {
    var json = {};
    for(var i = 0; i < data.length; i++) {
        if(!json[data[i].language]) {
            json[data[i].language] =data[i].languageId;
        }
    }
    return JSON.stringify(json);
}
